﻿using System.Web.Mvc;
using AutoUpdateServer.Models;
using System.Linq;

namespace AutoUpdateServer.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            using (autoUpdateContext db = new autoUpdateContext())
            {
                var apps = db.AppNames.ToList();
                ViewData["apps"] = apps;
            }
            return View();
        }

        /// <summary>
        /// 创建新的自动更新app
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        public ActionResult createApp(string appName)
        {
            try
            {
                using (autoUpdateContext db = new autoUpdateContext())
                {
                    var app = db.AppNames.Where(x => x.AppName.Equals(appName)).FirstOrDefault();
                    if (app != null && app.id > 0)
                    {
                        return Content("已存在相同的appName");
                    }
                    app = new AppNames() { AppName = appName, AppState = "自动更新", AppVersion = 1, descrption = "" };
                    db.AppNames.Add(app);
                    int count = db.SaveChanges();
                    if (count > 0)
                    {
                        // 创建目录
                        System.IO.Directory.CreateDirectory(Server.MapPath("~") + @"UpdateFiles\" + appName);
                        return Content("ok");
                    }
                }
            }
            catch (System.Exception ex)
            {
                return Content(ex.Message);
            }

            return Content("添加失败");
        }

        /// <summary>
        /// 修改版本号,描述等信息
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        public ActionResult saveAppInfo(AppNames appName)
        {
            if (appName != null && appName.id > 0)
            {
                using (autoUpdateContext db = new autoUpdateContext())
                {
                    var app = db.AppNames.Where(x => x.id == appName.id).FirstOrDefault();
                    if (app != null && app.id > 0)
                    {
                        app.AppState = appName.AppState == null ? "自动更新" : appName.AppState;
                        app.AppVersion = appName.AppVersion;
                        app.descrption = appName.descrption == null ? "" : appName.descrption;
                        var count = db.SaveChanges();
                        return Content(count.ToString());
                    }
                }
            }
            return Content("-1");
        }

        /// <summary>
        /// 将指定应用程序的文件读取到 文件列表中
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult scanAppPath(int id = 0)
        {
            if (id <= 0)
            {
                return Content("-1");
            }

            try
            {
                using (autoUpdateContext db = new autoUpdateContext())
                {
                    var app = db.AppNames.Where(x => x.id == id).FirstOrDefault();
                    if (app != null && app.id > 0)
                    {
                        var mapPath = Server.MapPath("~");
                        var dirPath = mapPath + @"UpdateFiles\" + app.AppName;
                        if (System.IO.Directory.Exists(dirPath))
                        {
                            var dir = new System.IO.DirectoryInfo(dirPath);
                            var fsd = new util.fileSacnByDir(dir);
                            var files = fsd.fileList;
                            var temp = db.FileNames.Where(x => x.AppID == app.id).ToList();
                            foreach (var item in temp)
                            {
                                var ent = db.Entry<FileNames>(item);
                                ent.State = System.Data.Entity.EntityState.Deleted;
                            }
                            db.SaveChanges();   // 先清除旧数据
                            foreach (var item in files)
                            {
                                var filename = new FileNames()
                                {
                                    AppID = id,
                                    descrption = "",
                                    fileHashCode = fsd.fileHashCode(item),
                                    fileLength = item.Length,
                                    fileName = item.Name,
                                    fileRealtiveName = item.FullName.Replace(mapPath + @"UpdateFiles\" + app.AppName + @"\", ""),
                                    filePath = item.FullName,
                                    fileState = "更新"
                                };
                                db.FileNames.Add(filename);
                            }
                            int count = db.SaveChanges();
                            return Content(count.ToString());
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbe)
            {
                string error = string.Empty;
                foreach (var item in dbe.EntityValidationErrors)
                {
                    foreach (var err in item.ValidationErrors)
                    {
                        error += ("属性名称:" + err.PropertyName + "错误信息:" + err.ErrorMessage);
                    } 
                }
                return Content(error);
            }
            catch (System.Exception ex)
            {
                return Content(ex.Message);
            }

            return Content("-2");
        }

        /// <summary>
        /// 修改某个文件的信息
        /// </summary>
        /// <param name="finame"></param>
        /// <returns></returns>
        public ActionResult changeFileInfo(FileNames finame)
        {
            if (finame != null && finame.id > 0)
            {
                using (autoUpdateContext db = new autoUpdateContext())
                {
                    var fi = db.FileNames.Where(x => x.id == finame.id).FirstOrDefault();
                    fi.descrption = finame.descrption == null ? "" : finame.descrption;
                    fi.fileState = finame.fileState;
                    var count = db.SaveChanges();
                    return Content(count.ToString());
                }
            }
            return Content("0");
        }

        /// <summary>
        /// 查看指定app的文件列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult fileList(int id = 0)
        {
            if (id <= 0)
            {
                return Content("参数错误");
            }
            using (autoUpdateContext db = new autoUpdateContext())
            {
                var files = db.FileNames.Where(x => x.AppID == id).ToList();
                ViewData["files"] = files;
            }
            return View();
        }




        #region 客户端接口

        /// <summary>
        /// 根据应用程序名称,获取版本号, 如果停止更新 0, 参数错误 -1
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        public ActionResult version(string appName)
        {
            if (string.IsNullOrWhiteSpace(appName))
            {
                return Content("-1");
            }

            using (autoUpdateContext db = new autoUpdateContext())
            {
                var app = db.AppNames.Where(x => x.AppName.Equals(appName) && x.AppState.Equals("自动更新")).FirstOrDefault();
                if (app != null && app.id > 0)
                {
                    return Content(app.AppVersion.ToString());
                }
            }
            return Content("0");
        }

        /// <summary>
        /// 获取需要下载更新(或删除的)的文件列表, 返回json数据
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        public ActionResult getFileList(string appName)
        {
            if (string.IsNullOrWhiteSpace(appName))
            {
                return Content("fail");
            }

            using (autoUpdateContext db = new autoUpdateContext())
            {
                var app = db.AppNames.Where(x => x.AppName.Equals(appName)).FirstOrDefault();
                if (app != null && app.id > 0)
                {
                    var fileList = db.FileNames.Where(x => x.AppID == app.id
                    && (x.fileState.Equals("更新") || x.fileState.Equals("删除"))).ToList();
                    if (fileList != null && fileList.Count > 0)
                    {
                        return Json(fileList, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            return Content("0");
        }

        /// <summary>
        /// 检测服务端文件是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult fileExist(int id)
        {
            using (autoUpdateContext db = new autoUpdateContext())
            {
                var file = db.FileNames.Where(x => x.id == id).FirstOrDefault();
                if (file != null && file.id > 0)
                {
                    if (System.IO.File.Exists(file.filePath))
                    {
                        return Content("1");
                    }
                }
            }
            return Content("0");
        }

        /// <summary>
        /// 根据文件id开始下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult downFile(int id)
        {
            using (autoUpdateContext db = new autoUpdateContext())
            {
                var file = db.FileNames.Where(x => x.id == id).FirstOrDefault();
                if (file != null && file.id > 0)
                {
                    return File(file.filePath, "application/octet-stream", file.fileName);
                }
            }
            return Content("文件不存在");
        }

        #endregion
    }
}